package com.anos.smsfun.fragment;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import android.widget.Toast;

import com.anos.smsfun.R;
import com.anos.smsfun.activities.ContactDetailActivity;
import com.anos.smsfun.activities.ViewSmsConversationActivity;
import com.anos.smsfun.adapter.ContactsAdapter;
import com.anos.smsfun.cache.SMSFunDataCache;
import com.anos.smsfun.cache.SMSFunDataCache.OnDataChangedListener;
import com.anos.smsfun.controller.DataRequestCallback;
import com.anos.smsfun.customview.IndexableListView;
import com.anos.smsfun.model.ContactsWrapper;
import com.anos.smsfun.task.DoingBackground;
import com.anos.smsfun.task.QueryUtils;
import com.anos.smsfun.utility.DefConstants;
import com.anos.smsfun.utility.Utils;

public class ContactsFragment extends LoadingStateFragment implements
		OnItemClickListener, OnQueryTextListener, OnItemLongClickListener {

	private IndexableListView mContactListView;
	private ContactsAdapter mContactsAdapter;
	private ArrayList<ContactsWrapper> mContactsWrappers = new ArrayList<ContactsWrapper>();
	private ProgressDialog mDialogLoading;
	private SearchView mSearchView;

	private SMSFunDataCache mSmsFunDataCache;

	private ContactsWrapper mContactSelected;

	/**
	 * Lưu trữ trạng thái có đang load dữ liệu hay không, tránh gọi load dữ liệu
	 * trùng lặp không cần thiết
	 * 
	 */
	private boolean mIsContactListLoading = false;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_contacts, container,
				false);
		// find view id
		findViewByIdAll(view);

		// init data cache
		mSmsFunDataCache = SMSFunDataCache.getInstance(getActivity());

		if (mContactsWrappers.size() == 0)
			mContactsWrappers = mSmsFunDataCache.getContactList();

		if (mContactsWrappers != null && mContactsWrappers.size() > 0) {
			mContactsAdapter = new ContactsAdapter(getActivity(),
					mContactsWrappers);
			mContactListView.setAdapter(mContactsAdapter);
		} else {
			mDialogLoading = new ProgressDialog(getActivity());
			mDialogLoading.setMessage(getActivity().getResources().getString(
					R.string.loading_contact));
			mDialogLoading.setCanceledOnTouchOutside(false);
			mDialogLoading.show();

			getContactList();
		}

		return view;
	}

	private void findViewByIdAll(View view) {
		mContactListView = (IndexableListView) view
				.findViewById(R.id.listview_contacts);
		mSearchView = (SearchView) view
				.findViewById(R.id.svSearchContact_contacts);

		// custom searchview
		customSearchView();

		mContactListView.setFastScrollEnabled(true);
		mContactListView.setOnItemClickListener(this);
		mContactListView.setOnItemLongClickListener(this);

		mSearchView.setOnQueryTextListener(this);

		registerForContextMenu(mContactListView);
	}

	/**
	 * custom search view
	 */
	private void customSearchView() {
		int id = mSearchView.getContext().getResources()
				.getIdentifier("android:id/search_src_text", null, null);
		int searchButtonId = getResources().getIdentifier(
				"android:id/search_button", null, null);
		int closeButtonId = getResources().getIdentifier(
				"android:id/search_close_btn", null, null);

		TextView textView = (TextView) mSearchView.findViewById(id);
		textView.setTextColor(Color.WHITE);
		textView.setHintTextColor(Color.WHITE);

		ImageView searchIconImg = (ImageView) mSearchView
				.findViewById(searchButtonId);
		searchIconImg.setImageResource(R.drawable.ic_search);

		ImageView closeIconImg = (ImageView) mSearchView
				.findViewById(closeButtonId);
		closeIconImg.setImageResource(R.drawable.ic_search_close);
	}

	/**
	 * get list contact
	 */
	private void getContactList() {
		mIsContactListLoading = true;
		DoingBackground.getContactList(getActivity(), mContactListCallback);
	}

	private OnDataChangedListener mDataSetChangedListener = new OnDataChangedListener() {

		@Override
		public void onDataChanged(int type) {
			if (type == TYPE_0 && !mIsContactListLoading) {
				getContactList();
			}
		}
	};

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mContactsWrappers.clear();
		SMSFunDataCache.getInstance(getActivity())
				.registerOnDataChangedListener(mDataSetChangedListener);

	}

	private DataRequestCallback<ArrayList<ContactsWrapper>> mContactListCallback = new DataRequestCallback<ArrayList<ContactsWrapper>>() {

		@Override
		public void onResult(ArrayList<ContactsWrapper> result,
				boolean continueWaiting) {
			Context c = getActivity();
			if (c == null) {
				return;
			}

			if (result != null && !result.isEmpty()) {
				mContactsWrappers.addAll(result);

				mContactsAdapter = new ContactsAdapter(getActivity(),
						mContactsWrappers);
				mContactListView.setAdapter(mContactsAdapter);
				mContactsAdapter.notifyDataSetChanged();

				// save database
				mSmsFunDataCache.saveContactsList(mContactsWrappers);
			} else {
				if (!continueWaiting) {
					// Có lỗi xảy ra khi request dữ liệu
					Toast.makeText(c, R.string.loading_error_toast,
							Toast.LENGTH_LONG).show();
				}
			}
			if (mDialogLoading.isShowing())
				mDialogLoading.dismiss();

			// Cập nhật trạng thái load dữ liệu
			mIsContactListLoading = continueWaiting;
		}
	};

	@Override
	public boolean isLoading() {
		return mIsContactListLoading;
	}

	@Override
	public void onItemClick(AdapterView<?> av, View v, int position, long id) {
		callIntentDetail(mContactsWrappers.get(position));
	}

	@SuppressLint("DefaultLocale")
	@Override
	public boolean onQueryTextChange(String newText) {
		try {
			final ArrayList<ContactsWrapper> lstSearchResult = new ArrayList<ContactsWrapper>();
			for (int i = 0; i < mContactsWrappers.size(); i++) {
				// search display name
				String strDisplayName = mContactsWrappers.get(i)
						.getDisplayName().trim().toUpperCase();
				String strPhoneNumber = mContactsWrappers.get(i)
						.getDisplayNumber().trim();
				newText = newText.replace("0", "+84");
				if (newText.length() <= strDisplayName.length()
						|| newText.length() <= strPhoneNumber.length()) {
					if (strDisplayName.indexOf(newText.trim().toUpperCase()) != -1
							|| strPhoneNumber.indexOf(newText) != -1) {
						lstSearchResult.add(mContactsWrappers.get(i));
					}
				}
			}
			// refresh list
			mContactsAdapter = new ContactsAdapter(getActivity(),
					lstSearchResult);
			mContactListView.setAdapter(mContactsAdapter);
			mContactsAdapter.notifyDataSetChanged();

			// on item click
			mContactListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> av, View v,
						int position, long id) {
					callIntentDetail(lstSearchResult.get(position));
				}
			});

		} catch (Exception e) {
			return false;
		}
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		return false;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.listview_contacts) {
			// IndexableListView lv = (IndexableListView) v;
			AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
			mContactSelected = (ContactsWrapper) mContactsWrappers
					.get(acmi.position);

			String title = "Option";
			if (mContactSelected != null)
				title = mContactSelected.getDisplayName();
			menu.setHeaderTitle(title);
			menu.add(Menu.NONE, DefConstants.MNU_CONTEXT_CONTACT_CALL_ID,
					Menu.NONE, getString(R.string.mnu_call));
			menu.add(Menu.NONE, DefConstants.MNU_CONTEXT_CONTACT_SEND_ID,
					Menu.NONE, getString(R.string.mnu_send));
			menu.add(Menu.NONE, DefConstants.MNU_CONTEXT_CONTACT_SHARE_ID,
					Menu.NONE, getString(R.string.mnu_share));
			menu.add(Menu.NONE, DefConstants.MNU_CONTEXT_CONTACT_EDIT_ID,
					Menu.NONE, getString(R.string.mnu_edit));
			menu.add(Menu.NONE, DefConstants.MNU_CONTEXT_CONTACT_DELETE_ID,
					Menu.NONE, getString(R.string.mnu_delete));
		}
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case DefConstants.MNU_CONTEXT_CONTACT_CALL_ID:
			if (mContactSelected != null
					&& !mContactSelected.getDisplayNumber().trim().equals("")) {
				Utils.callPhone(getActivity(), mContactSelected
						.getDisplayNumber().trim());
			} else {
				Utils.showMessageDialog(getActivity(),
						getString(R.string.can_not_call));
			}
			break;
		case DefConstants.MNU_CONTEXT_CONTACT_SEND_ID:
			if (mContactSelected != null) {
				Intent intent = new Intent(getActivity(),
						ViewSmsConversationActivity.class);
				intent.putExtra(DefConstants.ACTION_VIEW_CONVERSATION,
						mContactSelected.getDisplayNumber().trim());
				getActivity().startActivity(intent);
				getActivity().overridePendingTransition(0,
						R.anim.exit_slide_left);
			}
			break;
		case DefConstants.MNU_CONTEXT_CONTACT_SHARE_ID:
			if (mContactSelected != null) {
				Utils.sendTextContent(getActivity(),
						mContactSelected.getDisplayName() + " ["
								+ mContactSelected.getDisplayNumber() + "]");
			}
			break;
		case DefConstants.MNU_CONTEXT_CONTACT_EDIT_ID:
			if (mContactSelected != null) {

			}
			break;
		case DefConstants.MNU_CONTEXT_CONTACT_DELETE_ID:
			if (mContactSelected != null) {
				Builder builder = new Builder(getActivity());
				builder.setTitle("Xoá");
				builder.setMessage("Xóa địa chỉ "
						+ mContactSelected.getDisplayName() + " ["
						+ mContactSelected.getDisplayNumber() + "]");
				builder.setPositiveButton(getActivity().getString(R.string.ok),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// delete
								QueryUtils.deleteContact(getActivity(),
										mContactSelected.getContactId());

								// refresh list
								mContactsWrappers.remove(mContactSelected);
								mContactsAdapter.notifyDataSetChanged();
							}
						});
				builder.setNegativeButton(
						getActivity().getString(R.string.cancel),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
			break;
		}
		mContactSelected = null;
		return super.onContextItemSelected(item);
	}

	/**
	 * goi start activity detail
	 */
	private void callIntentDetail(ContactsWrapper contactsWrapper) {
		if (contactsWrapper != null) {
			Intent intent = new Intent(getActivity(),
					ContactDetailActivity.class);
			intent.putExtra(DefConstants.ACTION_VIEW_DETAIL_CONTACT,
					contactsWrapper);
			getActivity().startActivity(intent);
			getActivity().overridePendingTransition(0, R.anim.exit_slide_left);
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> av, View v, int position,
			long id) {
		return false;
	}
}
